package com.mdlib.helper.ui.fragments.home;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.ljlib.core.base.BaseFragment;
import com.ljlib.core.util.EmptyUtils;
import com.ljlib.help.R;
import com.mdlib.helper.api.DataManager;
import com.mdlib.helper.api.network.RxHelper;
import com.mdlib.helper.api.network.RxSubscribe;
import com.mdlib.helper.common.MDConstant;
import com.mdlib.helper.event.CityEvnet;
import com.mdlib.helper.event.LocationEvent;
import com.mdlib.helper.model.AppModel;
import com.mdlib.helper.model.entity.AppInitEntity;
import com.mdlib.helper.model.entity.BannerEntity;
import com.mdlib.helper.model.entity.IndexService;
import com.mdlib.helper.model.entity.OneKeyServiceEntity;
import com.mdlib.helper.model.entity.SendMainServiceEntity;
import com.mdlib.helper.model.entity.UnReadMessage;
import com.mdlib.helper.model.entity.WebViewEntity;
import com.mdlib.helper.ui.UIHelper;
import com.mdlib.helper.ui.adapter.QuickServiceAdapter;
import com.mdlib.helper.ui.adapter.SendHomeMainServiceAdapter;
import com.mdlib.helper.ui.widget.springview.HelperHeads;
import com.mdlib.helper.ui.widget.springview.SpringView;
import com.mdlib.helper.utils.ToastUtil;
import com.mdlib.helper.utils.bga.BGABanner;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * 作者：HQY on 16/11/9 16:58
 * 邮箱：hqy_xz@126.com
 */

public class SendHomeFragment extends BaseFragment {


    private final String MINNETONKA = "2";
    private final String TAKE = "3";
    private final String ACGENCY = "1";

    private final String ROLE = "1";


    @Bind(R.id.banner_rush_carousel)
    BGABanner mBannerRushCarousel;

    @Bind(R.id.ll_home_location)
    LinearLayout mLlHomeLocation;
    @Bind(R.id.ll_home_vicinity)
    LinearLayout mLlHomeVicinity;


    @Bind(R.id.ll_home_refresh)
    LinearLayout mLlHomeRefresh;
    @Bind(R.id.sv_send_home)
    SpringView mSvSendHome;
    @Bind(R.id.rv_send_main_service)
    RecyclerView mRvSendMainService;
    @Bind(R.id.rv_quick_service)
    RecyclerView mRvQuickService;
    @Bind(R.id.tv_address_street)
    TextView mTvAddressStreet;
    @Bind(R.id.rl_send_message)
    RelativeLayout mRlSendMessage;
    @Bind(R.id.iv_send_home_message_tips)
    ImageView mIvSendHomeMessageTips;

    /**
     * 代买 代办 代送取 随意购
     */
    private List<SendMainServiceEntity> mainServiceList = new ArrayList<>();
    private SendHomeMainServiceAdapter mainServiceAdapter;

    /**
     * 一键服务
     *
     * @return
     */
    private List<OneKeyServiceEntity> oneKeyServiceList = new ArrayList<>();
    private QuickServiceAdapter quickServiceAdapter;


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_home_send_single;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onStart() {
        super.onStart();
        getUnreadMessage();
    }

    @Override
    protected void initView(View view) {
        init();
        mainService();
        quickService();
        getBanner();
        getService();
        getSystemInit();

    }

    /**
     * 代买 代办 代送取 随意购
     */
    public void mainService() {
        mainServiceAdapter = new SendHomeMainServiceAdapter(mainServiceList);
        mRvSendMainService.setLayoutManager(new GridLayoutManager(getActivity(), 4));
        mRvSendMainService.setAdapter(mainServiceAdapter);
        mRvSendMainService.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void SimpleOnItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {

            }

            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                super.onItemClick(adapter, view, position);
                switch (mainServiceList.get(position).getCode()) {
                    case 1:
                        UIHelper.showSendOrderOne(getActivity(), UIHelper.MONNETONKA);
                        break;
                    case 2:
                        UIHelper.showSendOrderOne(getActivity(), UIHelper.TAKE);
                        break;
                    case 3:
                        UIHelper.showAegency(getActivity(), null, UIHelper.AGENCY_TYPE_ONE);
                        break;
                    case 4:
                        UIHelper.showWeb(getActivity(), new WebViewEntity("随意购", AppModel.getInstance().getAppFrontInfo().getRandomBuy()));
                        break;

                }

            }
        });

    }

    /**
     * 一键服务
     */
    public void quickService() {
        quickServiceAdapter = new QuickServiceAdapter(oneKeyServiceList);
        mRvQuickService.setLayoutManager(new GridLayoutManager(getActivity(), 4));
        mRvQuickService.setAdapter(quickServiceAdapter);
        mRvQuickService.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void SimpleOnItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {

            }

            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                super.onItemClick(adapter, view, position);
                switch (oneKeyServiceList.get(position).getBus_type()) {
                    case MINNETONKA:

                        UIHelper.showSendOrderOne(getActivity(), UIHelper.MONNETONKA);
                        break;
                    case TAKE:
                        UIHelper.showSendOrderOne(getActivity(), UIHelper.TAKE);
                        break;
                    case ACGENCY:
                        UIHelper.showAegency(getActivity(), oneKeyServiceList.get(position), UIHelper.AGENCY_TYPE_TWO);
                        break;
                    default:
                        ToastUtil.showToast(oneKeyServiceList.get(position).getName());
                        break;
                }
            }
        });

    }

    /**
     * 接口  获取服务
     */
    public void getService() {
        addSubscribe(DataManager.getInstance().getUserApi()
                .getIndexService()
                .compose(RxHelper.<IndexService>defaultHandleResult())
                .subscribe(new RxSubscribe<IndexService>() {
                    @Override
                    protected void onSucc(IndexService indexService) {
                        mainServiceList = indexService.getMainService();
                        mainServiceAdapter.setNewData(mainServiceList);
                        mRvSendMainService.setLayoutManager(new GridLayoutManager(getActivity(), mainServiceList.size()));
                        mainServiceAdapter.notifyDataSetChanged();
                        oneKeyServiceList = indexService.getFastService();
                        quickServiceAdapter.setNewData(oneKeyServiceList);
                        quickServiceAdapter.notifyDataSetChanged();
                        mSvSendHome.onFinishFreshAndLoad();

                    }

                    @Override
                    protected void onFail(String msg) {
                        ToastUtil.showToast(msg);
                        mSvSendHome.onFinishFreshAndLoad();

                    }
                }));

    }

    /**
     * 轮播图
     */
    public void getBanner() {
        addSubscribe(DataManager.getInstance().getUserApi()
                .getBanner(ROLE, MDConstant.PLATFORM)
                .compose(RxHelper.<ArrayList<BannerEntity>>defaultHandleResult())
                .subscribe(new RxSubscribe<ArrayList<BannerEntity>>() {
                    @Override
                    protected void onSucc(final ArrayList<BannerEntity> bannerEntities) {
                        List<String> imgs = new ArrayList<String>();
                        for (int i = 0; i < bannerEntities.size(); i++) {
                            String img = "http://www."+bannerEntities.get(i).getPath();
                            //String img = bannerEntities.get(i).getPath();
                            imgs.add(img);
                        }
                        if (!EmptyUtils.isEmpty(imgs)) {
                            mBannerRushCarousel.setData(imgs, null);
                            mBannerRushCarousel.setAdapter(new BGABanner.Adapter() {
                                @Override
                                public void fillBannerItem(BGABanner banner, View view, Object model, int position) {
                                    Glide.with(getActivity()).load(model).into((ImageView) view);
                                }
                            });
                            mBannerRushCarousel.setOnItemClickListener(new BGABanner.OnItemClickListener() {
                                @Override
                                public void onBannerItemClick(BGABanner banner, View view, Object model, int position) {
                                    UIHelper.showWeb(getActivity(), new WebViewEntity("", bannerEntities.get(position).getUrl()));
                                }
                            });
                        }
                        mSvSendHome.onFinishFreshAndLoad();
                    }

                    @Override
                    protected void onFail(String msg) {
                        ToastUtil.showToast(msg);
                        mSvSendHome.onFinishFreshAndLoad();

                    }
                }));
    }


    /**
     * 初始化
     */
    public void init() {
        mLlHomeRefresh.setVisibility(View.GONE);
        mLlHomeVicinity.setVisibility(View.VISIBLE);
        mSvSendHome.setType(SpringView.Type.FOLLOW);
        mSvSendHome.setListener(new SpringView.OnFreshListener() {
            @Override
            public void onRefresh() {
                getBanner();
                getService();
                getSystemInit();
            }

            @Override
            public void onLoadmore() {

            }
        });
        mSvSendHome.setHeader(new HelperHeads(getActivity()));
    }

    /**
     * 登陆后获取初始化参数
     */
    private void getSystemInit() {
        addSubscribe(DataManager.getInstance().getUserApi()
                .getSystemInit()
                .compose(RxHelper.<AppInitEntity>defaultHandleResult())
                .subscribe(new RxSubscribe<AppInitEntity>() {
                    @Override
                    protected void onSucc(AppInitEntity appInitEntity) {
                        AppModel.getInstance().setAppInitEntity(appInitEntity);
                        AppModel.getInstance().writeToCache();
                    }

                    @Override
                    protected void onFail(String msg) {
                        ToastUtil.showToast(msg);

                    }
                }));
    }

    /**
     * 获取未读数量
     */
    private void getUnreadMessage() {
        addSubscribe(DataManager.getInstance().getUserApi()
                .getUnreadMessage()
                .compose(RxHelper.<UnReadMessage>defaultHandleResult())
                .subscribe(new RxSubscribe<UnReadMessage>() {
                    @Override
                    protected void onSucc(UnReadMessage unReadMessage) {
                        if (unReadMessage.getUnreadNum() > 0) {
                            mIvSendHomeMessageTips.setVisibility(View.VISIBLE);
                        } else {
                            mIvSendHomeMessageTips.setVisibility(View.GONE);

                        }
                    }

                    @Override
                    protected void onFail(String msg) {
                        ToastUtil.showToast(msg);
                    }
                }));
    }

    @OnClick({R.id.ll_home_location, R.id.ll_home_vicinity, R.id.rl_send_message})
    public void onClick(View view) {
        switch (view.getId()) {

            case R.id.ll_home_location:
                UIHelper.showCity(getActivity());
                break;
            case R.id.ll_home_vicinity:
                UIHelper.shwoSendVicinity(getActivity());
                break;
            case R.id.rl_send_message:
                UIHelper.showMessage(getActivity());
                break;

        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(LocationEvent locationEvent) {
        if (locationEvent.getStart().equals("0")) {
            mTvAddressStreet.setText(AppModel.getInstance().getAppLocationEntity().getStreet());
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(CityEvnet cityEvnet) {
        mTvAddressStreet.setText(cityEvnet.getCityName());
    }


}
